package com.shouhe.mysap.controller.sale;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shouhe.mysap.common.MySapResult;
import com.shouhe.mysap.common.PageResult;
import com.shouhe.mysap.common.status.PlanStatus;
import com.shouhe.mysap.common.status.SaleStatus;
import com.shouhe.mysap.entity.*;
import com.shouhe.mysap.service.*;
import com.shouhe.mysap.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * 销售订单控制器
 * sale_order表
 * </p>
 *
 * @author 守鹤
 * @since 2020-06-01
 */
@RestController
@RequestMapping("/sale-order")
public class SaleOrderController {

    @Autowired
    private SaleOrderService saleOrderService;

    @Autowired
    private TechBomService techBomService;

    @Autowired
    private PurPriceService purPriceService;

    @Autowired
    private PlanPlaceService planPlaceService;

    @Autowired
    private PlanNoSupplierService planNoSupplierService;

    @Autowired
    private PlanSaleOrderService planSaleOrderService;

    /**
     * 分页查询全部的销售商品
     *
     * @param page        前端传递的页码
     * @param rows        前端传递的显示条数
     * @param saleName    销售组
     * @param saleOrderId 销售订单id
     * @param itemName    商品名称
     * @return 分页显示对象
     */
    @RequestMapping("/getSaleOrders")
    public PageResult getSaleOrders(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam(defaultValue = "null") String saleName, @RequestParam(defaultValue = "null") String saleOrderId, @RequestParam(defaultValue = "null") String itemName) {
        Map<String, Object> likeMap = new HashMap<>();
        likeMap.put("sale_order_id", saleOrderId);
        likeMap.put("sale_name", saleName);
        likeMap.put("item_name", itemName);
        PageResult pageResult = PageResultUtil.getPageResultEqLikeMap(page, rows, saleOrderService, null, likeMap);
        return pageResult;
    }

    /**
     * @描述 根据订单状态得到销售订单,
     * @参数
     * @返回值
     */
    @RequestMapping("/getSaleOrderByStatus")
    public PageResult getSaleOrderByStatus(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, Integer[] status) {
        PageResult pageResult = PageResultUtil.getPageResult(page, rows, saleOrderService, status);
        return pageResult;
    }

    /**
     * 根据id 得到一个销售订单id
     *
     * @param id id
     * @return
     */
    @RequestMapping("/getSaleOrderById")
    public SaleOrder getSaleOrderById(Integer id) {
        SaleOrder saleOrder = SelectUtil.selectOneEq("id", id, saleOrderService);
        return saleOrder;
    }

    /**
     * 返回一个销售订单id 默认以 1 开头
     *
     * @return 前端接收的执行结果对象
     */
    @RequestMapping("/getSaleOrderId")
    public Integer getSaleOrderId() {
        IDUtil.getNewPurOrderId();
        return null;
    }

    /**
     * 根据销售订单id，得到当前销售订单最大行号，追加销售订单时用
     *
     * @param saleOrderId 销售订单id
     * @return 前端接收的执行结果对象
     */
    @RequestMapping("/getSaleOrderMaxRow")
    public Integer getSaleOrderMaxRow(String saleOrderId) {
        int row = 10;
        List<SaleOrder> list = SelectUtil.selectListEq("sale_order_id", saleOrderId, saleOrderService);
        if (list == null || list.size() == 0) {
            return row;
        }
        //得到当前最大行号
        for (SaleOrder order : list) {
            Integer max = order.getSaleOrderRow();
            if (max > row) {
                row = max;
            }
        }
        //返回时，最大行号加10
        return row + 10;
    }

    /**
     * 添加一个销售订单
     *
     * @param saleOrder 销售订单对象
     * @return 前端接收的执行结果对象
     */
    @RequestMapping("/addSaleOrder")
    @Transactional
    public MySapResult addSaleOrder(SaleOrder saleOrder) {
        return AddUtil.addObject("添加销售订单", saleOrder, saleOrderService);
    }


    /**
     * 更新一个销售订单，默认不更新客户编码。如果要更新客户编码，则同一张订单的客户编码全部都要改
     *
     * @param saleOrder 销售订单对象
     * @param selected  是否修改客户对象
     * @return 前端接收的执行结果对象
     */
    @RequestMapping("/updateSaleOrder")
    @Transactional
    public MySapResult updateSaleOrder(SaleOrder saleOrder, boolean selected) {
        try {
            if (selected) {
                String saleOrderId = saleOrder.getSaleOrderId();
                List<SaleOrder> orders = SelectUtil.selectListEq("sale_order_id", saleOrderId, saleOrderService);
                List<PlanSaleOrder> planSaleOrders = SelectUtil.selectListEq("sale_order_id", saleOrderId, planSaleOrderService);
                for (SaleOrder order : orders) {
                    order.setClientCode(saleOrder.getClientCode());
                }
                for (PlanSaleOrder order : planSaleOrders) {
                    order.setClientCode(saleOrder.getClientCode());
                }
                UpdateUtil.updateObjectListById("更新销售商品全部客户的id", orders, saleOrderService);
                UpdateUtil.updateObjectListById("更新供应链销售商品全部客户的id", planSaleOrders, planSaleOrderService);
            }
            //如果不点修改客户选项，默认不修改客户编码
            saleOrder.setClientCode(null);
            boolean b = saleOrderService.updateById(saleOrder);
            MySapResult result = PrintUtil.succOrErr(b, "更新销售商品", saleOrder.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return PrintUtil.succOrErr(false, "更新销售商品", saleOrder.toString());
        }
    }

    /**
     * 根据id，更新一个销售订单的状态,
     *
     * @param id     id
     * @param status 销售订单的状态
     * @return 前端接收的执行结果对象
     */
    @RequestMapping("/updateSaleOrderStatusById")
    @Transactional
    public MySapResult updateSaleOrderStatusById(Integer id, Integer status) {
        return UpdateUtil.updateObjectById("更新销售订单状态", new SaleOrder().setId(id).setStatus(status), saleOrderService);
    }

    /**
     * @描述 将销售订单交给供应链确认
     * @参数
     * @返回值
     */
    @RequestMapping("/planConfirmSaleOrder")
    @Transactional
    public MySapResult planConfirmSaleOrder(Integer id, Integer status) {
        MySapResult result = updateSaleOrderStatusById(id, status);
        if (!result.isSuccess()) {
            return result;
        }
        SaleOrder saleOrder = SelectUtil.selectOneEq("id", id, saleOrderService);
        //供应链销售订单中需要增加记录
        PlanSaleOrder planSaleOrder = new PlanSaleOrder();
        BeanUtils.copyProperties(saleOrder, planSaleOrder);
        planSaleOrder.setId(null);
        planSaleOrder.setDeleted(0);
        planSaleOrder.setVersion(0);
        planSaleOrder.setCreateTime(null);
        planSaleOrder.setUpdateTime(null);
        planSaleOrder.setPlanTime(null);
        MySapResult result2 = AddUtil.addObject("添加一个销售订单到供应链", planSaleOrder, planSaleOrderService);
        if (!result2.isSuccess()) {
            return result2;
        }
        //查出当前商品全部的Bom
        List<TechBom> boms = SelectUtil.selectListEq("item_code", saleOrder.getItemCode(), techBomService);
        for (TechBom bom : boms) {
            String thingCode = bom.getThingCode();
            List<PurPrice> purPrices = SelectUtil.selectListEq("thing_code", thingCode, purPriceService);
            if (purPrices != null && purPrices.size() > 0) {
                for (PurPrice purPrice : purPrices) {
                    //价格财务已经审核，并且是主供应商
                    if (purPrice.getStatus() == 1 && purPrice.getMainSupplier() == 1) {
                        //添加到供应链下单视图中
                        PlanPlace planPlace = new PlanPlace();
                        BeanUtils.copyProperties(saleOrder, planPlace);
                        BeanUtils.copyProperties(purPrice, planPlace);
                        planPlace.setId(null);
                        planPlace.setStatus(PlanStatus.PLAN_PLACE_CAN_PLANPLACE);
                        planPlace.setDeleted(0);
                        planPlace.setVersion(0);
                        planPlace.setCreateTime(null);
                        planPlace.setUpdateTime(null);
                        planPlace.setPlanTime(null);
                        MySapResult result1 = AddUtil.addObject("销售订单Bom添加到供应链下单视图中", planPlace, planPlaceService);
                        if (!result1.isSuccess()) {
                            return result1;
                        }
                    } else if (purPrice.getStatus() == 1 && purPrice.getMainSupplier() != 1) {
                        //财务已审核价格，但是这条数据不是主供应商
                        PlanNoSupplier noSupplier = new PlanNoSupplier();
                        BeanUtils.copyProperties(purPrice, noSupplier);
                        BeanUtils.copyProperties(saleOrder, noSupplier);
                        noSupplier.setId(null);
                        noSupplier.setStatus(PlanStatus.PLAN_NO_SUPPLIER_NO_SUPPLIER);
                        noSupplier.setDeleted(0);
                        noSupplier.setVersion(0);
                        noSupplier.setCreateTime(null);
                        noSupplier.setUpdateTime(null);
                        noSupplier.setPlanTime(null);
                        MySapResult result1 = AddUtil.addObject("销售订单Bom添加到供应链没有供应商视图中", noSupplier, planNoSupplierService);
                        if (!result1.isSuccess()) {
                            return result1;
                        }
                    } else if (purPrice.getStatus() == 0 && purPrice.getMainSupplier() == 1) {
                        //财务未审核价格，这条数据是主供应商
                        PlanNoSupplier noSupplier = new PlanNoSupplier();
                        BeanUtils.copyProperties(saleOrder, noSupplier);
                        BeanUtils.copyProperties(purPrice, noSupplier);
                        noSupplier.setId(null);
                        //状态为财务未审核
                        noSupplier.setStatus(PlanStatus.PLAN_NO_SUPPLIER_FINANCE_NOCHECK);
                        noSupplier.setDeleted(0);
                        noSupplier.setVersion(0);
                        noSupplier.setCreateTime(null);
                        noSupplier.setUpdateTime(null);
                        noSupplier.setPlanTime(null);
                        MySapResult result1 = AddUtil.addObject("销售订单Bom添加到供应链没有供应商视图中", noSupplier, planNoSupplierService);
                        if (!result1.isSuccess()) {
                            return result1;
                        }
                    }
                }
            } else {
                //没有数据
                PlanNoSupplier noSupplier = new PlanNoSupplier();
                BeanUtils.copyProperties(saleOrder, noSupplier);
                BeanUtils.copyProperties(bom, noSupplier);
                noSupplier.setId(null);
                noSupplier.setStatus(PlanStatus.PLAN_NO_SUPPLIER_PLAN_CONFIRM);
                noSupplier.setVersion(0);
                noSupplier.setCreateTime(null);
                noSupplier.setUpdateTime(null);
                noSupplier.setPlanTime(null);
                MySapResult result1 = AddUtil.addObject("销售订单Bom交给供应链确认", noSupplier, planNoSupplierService);
                if (!result1.isSuccess()) {
                    return result1;
                }
            }
        }

        return MySapResult.success("交给供应链确认成功");
    }


    /**
     * 更新多个销售订单的状态, 通过ids数组
     *
     * @param ids    id数组
     * @param status 销售订单状态
     * @return 前端接
     */
    @RequestMapping("/updateSaleOrdersStatusByIdArray")
    @Transactional
    public MySapResult updateSaleOrdersStatusByIdArray(@RequestParam("ids[]") Integer[] ids, Integer status) {
        List<SaleOrder> list = new ArrayList<>();
        if (ids == null) {
            return MySapResult.fail();
        }
        for (Integer id : ids) {
            SaleOrder saleOrder = new SaleOrder().setId(id).setStatus(status);
            list.add(saleOrder);
        }
        return UpdateUtil.updateObjectListById("更新销售订单状态", list, saleOrderService);
    }


    /**
     * @描述 通过 id数组 手动关闭销售订单
     * @参数
     * @返回值
     */
    @RequestMapping("/closeSaleOrders")
    @Transactional
    public MySapResult closeSaleOrders(@RequestParam("ids[]") Integer[] ids) {
        List<SaleOrder> list = new ArrayList<>();
        for (Integer id : ids) {
            SaleOrder order = new SaleOrder();
            order.setId(id);
            order.setStatus(SaleStatus.SALE_ORDER_CLOSED);
            list.add(order);
        }
        return UpdateUtil.updateObjectListById("手动关闭销售订单", list, saleOrderService);
    }


}

